package leetcode;

/**
 * 进制转换
 *
 * @author 王霄
 * @date 2022/2/14 20:40
 */
public class BaseConvert {

    /**
     * 进制枚举
     */
    public enum B {
        b2("01"),
        b4("0123"),
        b8("01234567"),
        b10("0123456789"),
        b16("0123456789abcdef"),
        b62("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
        private final String str;

        B(String str) {
            this.str = str;
        }

        public char[] chars() {
            return this.str.toCharArray();
        }
    }

    public static String tenToOther(int num, B b) {
        char[] chars = b.chars();
        if (num == 0) {
            return "0";
        }
        StringBuilder sb = new StringBuilder();
        while (num != 0) {
            int i = num % chars.length;
            sb.append(chars[i]);
            num = num / chars.length;
        }
        return sb.reverse().toString();
    }

    public static long otherTo10(String num, B b) {
        for (char c : b.chars()) {
            if (b.str.indexOf(c) == -1) {
                throw new RuntimeException(String.format("数字有误,[%s]中不含有%s", b.str, c));
            }
        }
        long result = 0;
        char[] chars = new StringBuilder(num)
                .reverse()
                .toString()
                .toCharArray();
        for (int i = 0; i < chars.length; i++) {
            result += b.str.indexOf(chars[i]) * Math.pow(b.str.length(), i);
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(tenToOther(1000000000, B.b2));
        System.out.println(otherTo10("1C", B.b62));
    }
}
